package com.aso114.project.mvp.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;
import android.widget.ImageView;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.util.Constant;
import com.netease.readwap.IHandlerCallback;
import com.netease.readwap.IReadWapCallback;
import com.netease.readwap.IRegisterNativeFunctionCallback;
import com.netease.readwap.ISetSDKAuthListener;
import com.netease.readwap.view.ReadWebView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ReadWapActivity extends AppCompatActivity {

    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    private ReadWebView mReadWebView;
    private ISetSDKAuthListener mISetSDKAuthListener;
    private boolean mIsYDH5;
    private String mAppChannel;
    private String mSDKAuth;
    SharedPreferences setting;
    public static void startReadWapActivity(Context context, boolean isAnonymous, String url) {
        Intent intent = new Intent(context, ReadWapActivity.class);
        intent.putExtra("isAnonymous", isAnonymous);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ButterKnife.bind(this);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        layoutTitleBarTitleTv.setText("网易云阅读");
//        initStatusBar();
        Intent intent = getIntent();
        boolean isAnonymous = intent.getBooleanExtra("isAnonymous", true);
        String url = intent.getStringExtra("url");

        mIsYDH5 = url.contains(Constant.YD_URL);
        mAppChannel = mIsYDH5 ? Constant.YD_APP_CHANNEL : Constant.MH_APP_CHANNEL;
        mSDKAuth = mIsYDH5 ? Constant.sYDSDKAuth : Constant.sMHSDKAuth;


        mReadWebView = findViewById(R.id.readwebView);

        // 设置IReadWapCallback
        mReadWebView.setReadWapCallback(mReadWapCallback);
        // 注册本地接口
        mReadWebView.registerNativeFunction(Constant.NATIVE_FUNCTION,
                mRegisterNativeFunctionCallback);

        setting = getSharedPreferences(Constant.SHARE_APP_TAG, 0);
        // 开始加载

        String user = setting.getString(Constant.SDKAuth, "");
        mReadWebView.startLoad(Constant.YD_URL, Constant.App_KEY, user);

        layoutTitleBarBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }


    /**
     * 设置状态栏的相关参数
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
    private void initStatusBar() {
        //判断Android版本是否支持透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            Window window = this.getWindow();
            View decorView = window.getDecorView();
            decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
                @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    return defaultInsets.replaceSystemWindowInsets(
                            defaultInsets.getSystemWindowInsetLeft(),
                            0,
                            defaultInsets.getSystemWindowInsetRight(),
                            defaultInsets.getSystemWindowInsetBottom());
                }
            });
            ViewCompat.requestApplyInsets(decorView);


        } else {
//            StatusBarUtil.setColor(this, R.drawable.title_gradient_background, true);
//            title1.setVisibility(View.GONE);
        }
    }


    private IReadWapCallback mReadWapCallback = new IReadWapCallback() {
        @Override
        public void doLogin(ISetSDKAuthListener setSDKAuthListener) {

        }

        @Override
        public void saveSDKAuth(String s) {
            setting.edit().putString(Constant.SDKAuth, s).apply();
        }
    };

    private IRegisterNativeFunctionCallback mRegisterNativeFunctionCallback = new
            IRegisterNativeFunctionCallback() {
        @Override
        public void onHandle(String handlerName, String value, IHandlerCallback handlerCallback) {
            String result = handle(handlerName, value);
            handlerCallback.onCallback(result);
        }
    };

    private String handle(String handlerName, String value) {
        if (handlerName.equals(Constant.NATIVE_FUNCTION)) {
            // 调用本地方法的具体实现
        }

        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == LoginActivity.REQUEST_CODE) {
//            if (resultCode == RESULT_OK) {
//                // 获取sdkAuth
//                new GetSDKAuthTask().execute();
//            }
//        }
    }

    class GetSDKAuthTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            Constant.sYDSDKAuth = Constant.YD_SDK_AUTH;
            Constant.sMHSDKAuth = Constant.MH_SDK_AUTH;
            mSDKAuth = mIsYDH5 ? Constant.sYDSDKAuth : Constant.sMHSDKAuth;

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (mISetSDKAuthListener != null) {
                mISetSDKAuthListener.setSDKAuth(mSDKAuth);
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mReadWebView.canGoBack()) {
                mReadWebView.goBack();

                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

}
